<template>
  <div class="foldable-text">
    <img style="width: 20px;height: 20px;margin-right: 4px;" src="~/assets/images/home/icon-notifiy.png" mode=""></img>
    <div :style="{
      maxHeight: expanded ? 'none' : '22px',
      overflow: expanded ? 'visible' : 'hidden',
      whiteSpace: expanded ? 'wrap' : 'nowrap',
    }" class="text-content" @click="showContact">
      {{ msg }}
    </div>
    <div @click="toggleExpand" class="expand-img">
      <img :style="{ transform: expanded ? 'rotate(180deg)' : '' }"
        style="transition: all 0.5s; width: 8px;height: 8px;" src="~/assets/images/home/icon-down.png" mode="">
      </img>
    </div>
  </div>
  <q-page class="home-page">

    <q-responsive :ratio="360 / 118">
      <div class="q-pa-md column justify-end">
        <div class="flex items-center">
          <div class="center q-mr-sm">
            <img src="~/assets/images/home/top-ok.png" alt="top-ok" style="width: 18px; height: 18px" />
          </div>
          <div style="font-size: 20px" class="text-weight-bold">恭喜您！</div>
        </div>
        <div class="" style="padding-left: 18px">
          <div class="q-pl-sm" style="font-size: 12px; color: #061c34">你的手机号已通过本平台额度初审！</div>
        </div>
      </div>
    </q-responsive>

    <section class="q-px-md">
      <div id="mainBox" class="form-panel q-pa-md form-panel-top" style="min-height: 100px; padding-bottom: 0px">
        <div>借多少（元）</div>
        <div class="flex items-end justify-center q-mt-sm">
          <div class="flex-1" style="width: 100px">
            <input class="full-width input-nostyle amount-input" type="number" inputmode="numeric" v-model="amount"
              placeholder="最多可借200000元" />
          </div>
          <div style="color: #1277ff; font-size: 12px; margin-bottom: 3px">（金额可修改）</div>
          <div @click="amount = undefined" class="center" style="
              padding: 2px;
              margin-bottom: 3px;
              color: #999999;
              background-color: #eaedf0;
              border-radius: 999px;
            ">
            <q-icon name="close" size="16px" />
          </div>
        </div>
        <div class="grid grid-flow-row grid-cols-3 q-mt-sm" style="gap: 8px">
          <div class="input-option center" :class="{ active: amount == 10000 }" @click="amount = 10000">
            借￥10000
          </div>
          <div class="input-option center" :class="{ active: amount == 20000 }" @click="amount = 20000">
            借￥20000
          </div>
          <div class="input-option center" :class="{ active: amount == 50000 }" @click="amount = 50000">
            借￥50000
          </div>
        </div>
        <div style="color: #999999; font-size: 12px" class="q-mt-sm">
          最高可借200000元，具体金额以最终审批结果为准
        </div>
      </div>
      <svg style="width: 100%; height: auto; display: block" viewBox="0 0 200 20" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <mask id="cutout">
            <rect width="200" height="50" fill="white" />
            <circle cx="0" cy="10" r="6" fill="black" />
            <circle cx="200" cy="10" r="6" fill="black" />
          </mask>
        </defs>

        <rect width="200" height="20" fill="white" mask="url(#cutout)" />
        <line x1="10" y1="10" x2="190" y2="10" stroke="#EAEDF0" stroke-width="1" stroke-dasharray="2,2" />
      </svg>
      <div class="form-panel q-pa-md form-panel-bottom" style="min-height: 100px; padding-top: 0">
        <div class="flex items-center justify-between">
          <div class="text-weight-bold">优惠劵</div>
          <div class="flex items-center text-right" @click="yhjTips">
            <div class="q-mr-xs">
              <div class="text-weight-bold">30天免息劵-提前结清失效</div>
              <div class="q-mt-xs" style="
                  font-size: 12px;
                  background-color: rgba(255, 82, 84, 0.1);
                  color: #ff5254;
                  padding: 3px 6px;
                  border-radius: 4px;
                ">
                若提前还清或逾期，本劵将失效
              </div>
            </div>
            <div class="center" style="color: #cccccc">
              <q-icon name="arrow_forward_ios" size="16px" />
            </div>
          </div>
        </div>
        <div class="line q-my-md" style="background-color: #f1f1f1; height: 1px"></div>
        <div class="flex items-center justify-between">
          <div class="text-weight-bold">还款期数</div>
          <div class="flex items-center text-right text-weight-bold">可选3，6，12，36期</div>
        </div>
        <div class="line q-my-md" style="background-color: #f1f1f1; height: 1px"></div>

        <div class="flex items-center justify-between">
          <div class="text-weight-bold">还款规则</div>
          <div class="text-right">
            <div class="text-weight-bold">随借随还</div>
            <div class="q-mt-xs" style="font-size: 12px; color: #999999">每日计算，提前还0手续费</div>
          </div>
        </div>
        <input type="tel" v-model="phone" inputmode="numeric" min="0" max="9" maxlength="11" autofocus
          @focus="inputPhoneFocus" @keydown="inputPhoneHandler" class="q-mt-md block full-width form-input"
          style="border: 0; outline: none; font-size: 16px" placeholder="输入手机号（已加密）" />

        <q-btn id="gotoBtn" class="full-width submit-btn animation-btn" unelevated @click="showPopup()">
          去提现
        </q-btn>
        <!-- <div class="pointer">
          <div class="white-point">
            <div class="white-point-in"></div>
          </div>
          <img src="~/assets/images/public/pointer.png" style="display: block; width: 45px" />
        </div> -->
        <div class="flex q-mt-md justify-center">
          <div :class="{ shake: isShaking }" class="center q-mr-xs" @click="isApprove = !isApprove">
            <img v-if="!isApprove" src="~/assets/images/public/nu_select.png" style="width: 15px" />
            <img v-else src="~/assets/images/public/ok_select.png" style="width: 15px" />
          </div>
          <div style="font-size: 12px; opacity: 0.7; color: #000;">
            <span @click="isApprove = true">我已阅读并同意</span><a
              @click="openPopup(0)" href="javascript:0;"
              style="color: #1277ff">《用户服务协议》</a><a
              @click="openPopup(1)" href="javascript:0;"
              style="color: #1277ff">《隐私政策》</a>
          </div>
        </div>
      </div>

      <div style="color: #b2b6bb; font-size: 12px; text-align: center; margin-top: 30px">
        <div>
          郑重声明：本平台提供贷款/融资咨询、推荐等助贷或助融服务，资金由银行或持牌金融机构提供，额度、到账时间以实际资金方审批结果为准,
          未成功到账前绝不收取任何费用，为了保证您的资金安全，请不要相信任何要求您支付费用的信息、邮件、电话等不实信息。
        </div>
        <div class="q-mt-md">理性借贷，避免逾期</div>
        <div>合理安排资金，珍惜个人信用</div>
        <div class="q-mt-md">{{ productInfo[pn].copyright }} {{ productInfo[pn].company }}</div>
        <a href="https://beian.miit.gov.cn/" style="color: inherit" target="_blank">{{ icpConfig }}</a>
        <div class="q-mt-md">{{ version }}</div>
      </div>
    </section>
    <div class="" style="height: 50px"></div>
    <VerificationCode ref="VerificationCodeRef" />
    <BackDialog ref="BackDialogRef" />
    <AgreementDialog ref="AgreementDialogRef" @confirm="submit"/>
    <ContactDialog :isShowUI="false" ref="ContactDialogRef" />
  </q-page>
</template>

<script setup lang="ts">
import { Button, showLoadingToast } from 'vant';
import { showToast } from 'vant';
import { nextTick, ref } from 'vue';
import VerificationCode from 'src/components/VerificationCode.vue';
import { VerificationCodeInstance } from 'src/components/VerificationCode';
import { useAppStore } from 'src/stores/app-store';
import { useRoute, useRouter } from 'vue-router';
import { useProtocolLink } from 'src/config/protocol_link';
import { getUrlParam } from 'src/boot/paramhandler';
import { useLoginHook } from 'src/hooks/login_hook';
import { useWebView } from '../webview/webview';
import BackDialog from 'src/components/BackDialog.vue';
import { BackDialogInstance } from 'src/components/BackDialog';
import ContactDialog from 'src/components/ContactDialog.vue';
import { ContactDialogInstance } from 'src/components/ContactDialog';
import AgreementDialog from 'src/components/AgreementDialog.vue';
import { AgreementDialogInstance } from 'src/components/AgreementDialog';
import { onMounted } from 'vue';
import { onUnmounted } from 'vue';
import { icpConfig } from 'src/config/icp.config';
import { version } from 'src/config/env.config';
import { isMobile } from 'mobile-device-detect';
import { productInfo } from 'src/config/env.config'
import { getConfigApi } from 'src/api/app';
const pn = localStorage.getItem('pn') || 'ayr'
const isApprove = ref(false);
const isShaking = ref(false)
const BackDialogRef = ref<BackDialogInstance>();
const ContactDialogRef = ref<ContactDialogInstance>();
const VerificationCodeRef = ref<VerificationCodeInstance>();
const AgreementDialogRef = ref<AgreementDialogInstance>();
const phone = ref('');
const router = useRouter();
const route = useRoute();
const isTheme = ref(false)
const amount = ref<number | undefined>(25000);
const erduNum = ref(0);
const scaleAnm = ref(false);
const expanded = ref(false);
const msg = ref("");
type sysConfig = {
  code: string;
  contentInfo: string;
  name: string;
};
const iniitEdruNum = async () => {
  const targetNum = 200000;
  if (erduNum.value < targetNum) {
    const temp = erduNum.value + 1111;
    if (temp < targetNum) {
      erduNum.value = temp;
      requestAnimationFrame(iniitEdruNum);
    } else {
      erduNum.value = targetNum;
      scaleAnm.value = true;
    }
  }
};

const inputPhoneHandler = (e: KeyboardEvent) => {
  if (!'1,2,3,4,5,6,7,8,9'.split(',').includes(e.key)) return;
  if (`${phone.value}`.length >= 11) {
    e.stopPropagation();
    e.preventDefault();
    return false;
  }
};

const inputPhoneFocus = () => {
  // const dom = document.querySelector('.q-page-container')
  // if (isMobile && dom && !['Win', 'win', 'Mac', 'mac'].some(item => window.navigator.platform.includes(item))) {
  //   dom.scrollTop = 160
  // }
}
const toggleExpand = () => {
  expanded.value = !expanded.value
}
const showContact = () => {
  ContactDialogRef.value?.show()
}
const enforceMaxLength = () => {
  if (phone.value.length > 11) {
    phone.value = phone.value.slice(0, 11);
  }
}
const yhjTips = () => {
  showToast('请点击“去提现”，进入借款页')
}
const triggerShake = () => {
  if (isShaking.value) return;

  isShaking.value = true;
  setTimeout(() => {
    isShaking.value = false;
  }, 500);
};
const showPopup = () => {
  const _phone = `${phone.value}`.trim();
  if (!_phone.length) {
    return showToast('请输入手机号');
  }
  if (!isApprove.value) {
    AgreementDialogRef.value?.show()
    // triggerShake()
    // showToast('请先同意协议');
    return 
  }
  submit()
}
const openPopup = (index: number = 0) => {
  AgreementDialogRef.value?.show(index)
}
const submit = async () => {
  const { pageType } = useAppStore();
  const _phone = `${phone.value}`.trim();
  isApprove.value = true;
  if (!_phone.length) {
    return showToast('请输入手机号');
  }
  if (!/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/.test(_phone)) {
    return showToast('手机号格式不正确');
  }
  if (useAppStore().isSMS) {
    VerificationCodeRef.value?.show(_phone);
    return;
  }
  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  await useAppStore().login(_phone);
  toast.close();
  useLoginHook(router, route).afterLoginHandler();
};

const popstateHandler = () => {
  BackDialogRef.value?.show();
  setTimeout(() => {
    window.history.pushState({ indexPage: true }, 'indexPage', window.location.href);
  });
};

onMounted(() => {
  window.history.pushState({ ...history.state }, '', window.location.href);
  // window.history.pushState({ indexPage: true }, 'indexPage', window.location.href);
  window.addEventListener('popstate', popstateHandler);
  getConfigMsg()
  iniitEdruNum();
  scrollToTarget()
});

onUnmounted(() => {
  window.removeEventListener('popstate', popstateHandler);
});
const scrollToTarget = () => {
  setTimeout(() => {
    nextTick(() => {
      const targetElement = document.getElementById('mainBox');
      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' });
      } else {
        console.error('Target element not found');
      }
    })
  }, 500)
}
const getConfigMsg = async () => {
  const res = await getConfigApi<sysConfig>({
    id: 5
  })
  msg.value = res.data.contentInfo
}
const initData = async () => {
  const { initPage, jointLogin, getUserInfo, isInitPage } = useAppStore();

  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  try {
    if (!isInitPage) await initPage();
    const { chargeType, isLogin } = useAppStore();
    const jointPhone = ((route.query.u as string) ?? '').trim();
    if (jointPhone && chargeType == 3) {
      await jointLogin(jointPhone);
      toast.close();
      return useLoginHook(router, route).afterLoginHandler();
    }
    if (isLogin) {
      await getUserInfo();
      toast.close();
      return useLoginHook(router, route).afterLoginHandler();
    }
  } catch (error) {
    console.error(error);
  }
  toast.close();
};
initData();
</script>

<style lang="scss" scoped>
.home-page {
  background-color: #eaedf0 !important;
  background-image: url(src/assets/images/home/bg.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
}

.foldable-text {
  box-sizing: content-box;
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 4px 12px;

  .expand-img {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .text-content {
    width: 85%;
    line-height: 17px;
    font-size: 12px;
    text-overflow: ellipsis;
    color: #1277FF;
    margin-top: 1px;
  }
}

.top1-bg {
  background-image: url(src/assets/images/home/bg-1.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.grid {
  display: grid;
}

.grid-flow-row {
  grid-auto-flow: row;
}

.grid-cols-3 {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.input-option {
  background-color: #f6f6f6;
  padding: 6px 4px;
  border: 1px solid #f6f6f6;
  border-radius: 8px;

  &.active {
    background-color: rgba($color: #1277ff, $alpha: 0.1);
    color: #1277ff;
    border: 1px solid #1277ff;
  }
}

.form-panel {
  background-color: #fff;
  $radius: 12px;

  &.form-panel-top {
    border-radius: $radius $radius 0 0;
  }

  &.form-panel-bottom {
    border-radius: 0 0 $radius $radius;
  }
}

.amount-input {
  font-size: 34px;
  padding-top: 10px;
  font-weight: 600;
  letter-spacing: 1px;
  line-height: 34px;
  color: #1277ff;

  &::placeholder {
    color: #999;
    letter-spacing: 0px;
    font-size: 20px;
  }
}

.form-input {
  background-color: #f4f6f9;
  border-radius: 9999px;
  padding: 12px 20px;
  font-weight: 900;

  &::placeholder {
    color: #999999;
  }
}

.pointer {
  position: absolute;
  right: calc(28% - 28px);
  top: 63%;
  z-index: 1;

  img {
    position: relative;
    z-index: 1;
    // animation: scale-anm 2s infinite;
  }

  .white-point {
    position: absolute;
    z-index: 0;
    background-color: rgba($color: #fff, $alpha: 0.2);
    border-radius: 9999px;
    $side: 18px;
    left: calc(-1 * $side / 2 + 1px);
    top: calc(-1 * $side / 2 + 3px);
    width: $side;
    height: $side;
    display: grid;
    place-content: center;

    .white-point-in {
      background-color: rgba($color: #fff, $alpha: 1);
      border-radius: 9999px;
      $side-in: 8px;
      width: $side-in;
      height: $side-in;
    }
  }
}

.submit-btn {
  background-color: #1277ff;
  color: #fff !important;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 1px;
  border-radius: 9999px;
  padding: 9px 18px !important;
  margin: 18px 0 0;
  color: #000;

  .tips {
    position: absolute;
    $width: 120px;
    width: $width;
    top: -0.225 * $width * 0.9;
    height: 0.225 * $width;
    background: url(src/assets/images/home/btn-tips.png) no-repeat;
    background-size: 100% 100%;
  }

}

.erdu-panel {
  background-image: url(src/assets/images/home/card-top.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 280px;
  height: 0.5218855218 * 280px;
  margin: 10px auto 0;
  position: relative;
  overflow: hidden;

  .content {
    position: absolute;
    z-index: 1;
    bottom: 4px;
    text-align: center;
    width: 100%;
  }

  &::after {
    content: '';
    display: block;
    position: absolute;
    bottom: -200%;
    left: 50%;
    width: 100%;
    height: 200%;
    background-color: #fff;
    animation: after-left 1s;
  }

  @keyframes after-left {
    0% {
      left: 0;
      bottom: 0%;
    }

    100% {
      left: 100%;
      bottom: -200%;
    }
  }
}

.scale-anm {
  animation: scale-anm 2s 2;
}

@keyframes scale-anm {
  0% {
    transform: scale(1);
  }

  25% {
    transform: scale(1.2);
  }

  50% {
    transform: scale(1);
  }

  75% {
    transform: scale(1.2);
  }

  100% {
    transform: scale(1);
  }
}

/* 抖动动画 */
@keyframes shake {
  0% {
    transform: translate(0, 0);
  }

  10% {
    transform: translate(-5px, -2px);
  }

  20% {
    transform: translate(5px, 2px);
  }

  30% {
    transform: translate(-5px, -2px);
  }

  40% {
    transform: translate(5px, 2px);
  }

  50% {
    transform: translate(-5px, -2px);
  }

  60% {
    transform: translate(5px, 2px);
  }

  70% {
    transform: translate(-5px, -2px);
  }

  80% {
    transform: translate(5px, 2px);
  }

  90% {
    transform: translate(-5px, -2px);
  }

  100% {
    transform: translate(0, 0);
  }
}

/* 动态添加的抖动类 */
.shake {
  animation: shake 0.5s ease;
}
</style>
